package cn.edu.zut.soft.student.service.class_.impl;

import cn.edu.zut.soft.student.bean.PageBean;
import cn.edu.zut.soft.student.dao.ClassMapper;
import cn.edu.zut.soft.student.model.Class;
import cn.edu.zut.soft.student.model.ClassExample;
import cn.edu.zut.soft.student.model.Student;
import cn.edu.zut.soft.student.service.class_.ClassBo;
import cn.edu.zut.soft.student.service.class_.vo.ClassQuery;
import cn.edu.zut.soft.student.service.student.StudentBo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author ChrisPhantom
 * @CreatDate 2021/02/22 17:00
 */

@Service
public class ClassBoImpl implements ClassBo {
    @Autowired
    private ClassMapper classMapper;

    @Autowired
    private StudentBo studentBo;

    @Override
    public int addClass(Class c) {
        return classMapper.insert(c);
    }

    @Override
    public int deleteClass(String classid) {
        List<Student> students = queryClassStudents(classid);
        students.forEach(student -> studentBo.deleteStudent(student.getStudentid()));
        return classMapper.deleteByPrimaryKey(classid);
    }

    @Override
    public int updateClass(Class c) {
        return classMapper.updateByPrimaryKey(c);
    }

    @Override
    public Class queryClassById(String classid) {
        return classMapper.selectByPrimaryKey(classid);
    }

    @Override
    public PageBean<List<Class>> queryClasses(ClassQuery classQuery) {
        ClassExample classExample = new ClassExample();
        classExample.setOffset(classQuery.getOffset());
        classExample.setLimit(classQuery.getLimit());
        ClassExample.Criteria criteria = classExample.createCriteria();
        if (classQuery.getClassid() != null && !"-1".equals(classQuery.getClassid())) {
            criteria.andClassidLike("%" + classQuery.getClassid() + "%");
        }
        if (classQuery.getClassname() != null && !"-1".equals(classQuery.getClassname())) {
            criteria.andClassnameLike("%" + classQuery.getClassname() + "%");
        }
        return new PageBean<>(classMapper.selectByExample(classExample), classMapper.countByExample(classExample));
    }

    @Override
    public List<Student> queryClassStudents(String classid) {
        return classMapper.queryClassStudents(classid);
    }
}
